﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Xml;

namespace Sinbiota.Web.Models
{
    public class GeoServerLayer
    {
        public string Id { get; set; }
        public string Title { get; set; }
        public string Style { get; set; }

    }

    public class GeoServerCapabilities
    {
        public string Url { get; set; }
        public IList<GeoServerLayer> Layers { get; set; }

        public GeoServerCapabilities()
        {
            Layers = new List<GeoServerLayer>();
        }

        public static GeoServerCapabilities FromXmlFile(string filepath)
        {
            //XmlReader x = XmlReader.Create();
            var reader = new XmlTextReader(filepath);
            var server = new GeoServerCapabilities();
            while (reader.Read())
            {
                if (reader.NodeType == XmlNodeType.Element && reader.Name.Equals("ows:ProviderName"))
                {
                    reader.Read();
                    server.Url = reader.Value.Replace("gwc/service/wmts","");
                }
                if (reader.NodeType == XmlNodeType.Element && reader.Name.Equals("Layer"))
                {
                    var layer = new GeoServerLayer();
                    server.Layers.Add(layer);
                    while (true)
                    {
                        reader.Read();
                        if (reader.NodeType == XmlNodeType.EndElement && reader.Name.Equals("Layer")) break;
                        if (reader.NodeType == XmlNodeType.Element && reader.Name.Equals("ows:Title"))
                        {
                            reader.Read();
                            layer.Title = reader.Value;
                            
                        }
                        if (reader.NodeType == XmlNodeType.Element && reader.Name.Equals("ows:Identifier"))
                        {
                            reader.Read();
                            layer.Id = reader.Value;
                            
                        }
                        if (reader.NodeType == XmlNodeType.Element && reader.Name.Equals("Style"))
                        {
                            do { 
                                reader.Read();
                            } while (reader.NodeType != XmlNodeType.Element || !reader.Name.Equals("ows:Identifier"));
                            reader.Read();
                            layer.Style = reader.Value;
                        }
                    }
                }

            }
            reader.Close();
            return server;

        }
    }


}